<template>
  <div class="admin-container">
    <div class="admin-card">
      <h2 class="admin-title">密码重置申请</h2>

      <div class="filter-section">
        <el-radio-group v-model="filterStatus" @change="fetchResetRequests">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="pending">待处理</el-radio-button>
          <el-radio-button label="processed">已处理</el-radio-button>
        </el-radio-group>
      </div>

      <div class="request-list" v-if="resetRequests.length > 0">
        <div v-for="request in resetRequests" :key="request.id" class="request-item">
          <div class="request-info">
            <div class="user-info">
              <span class="username">{{ request.user.username }}</span>
              <span class="role">{{ formatUserType(request.user.role) }}</span>
            </div>
            <div class="contact-info">
              <span class="email">{{ request.user.email }}</span>
            </div>
            <div class="request-meta">
              <span class="request-time">申请时间: {{ formatDate(request.created_at) }}</span>
              <span class="status" :class="request.is_processed ? 'processed' : 'pending'">
                {{ request.is_processed ? '已处理' : '待处理' }}
              </span>
            </div>
          </div>

          <div class="action-buttons" v-if="!request.is_processed">
            <el-button
              type="success"
              size="small"
              @click="handleReset(request.id, 'approve')"
              :loading="request.isApproving"
            >
              同意重置
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleReset(request.id, 'reject')"
              :loading="request.isRejecting"
            >
              拒绝
            </el-button>
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <el-empty description="暂无密码重置申请"></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'AdminResetPassword',
  data () {
    return {
      resetRequests: [],
      filterStatus: 'pending' // 默认显示待处理申请
    }
  },
  async created () {
    await this.fetchResetRequests()
  },
  methods: {
    async fetchResetRequests () {
      try {
        let url = '/api/password-reset/reset-requests/'
        if (this.filterStatus !== 'all') {
          url += `?status=${this.filterStatus}`
        }
        const { data } = await axios.get(url)
        this.resetRequests = data.map(req => ({
          ...req,
          isApproving: false,
          isRejecting: false
        }))
      } catch (error) {
        this.$notify.error({
          title: '错误',
          message: '获取重置申请失败',
          duration: 5000
        })
      }
    },
    formatUserType (role) {
      const roles = {
        1: '普通用户',
        2: '实验室管理员',
        3: '系统管理员'
      }
      return roles[role] || role
    },
    formatDate (date) {
      return moment(date).format('YYYY-MM-DD HH:mm')
    },
    async handleReset (requestId, action) {
      const request = this.resetRequests.find(r => r.id === requestId)
      if (!request) return

      if (action === 'approve') {
        request.isApproving = true
      } else {
        request.isRejecting = true
      }

      try {
        const { data } = await axios.post(`/api/password-reset/reset-requests/${requestId}/`, {
          action,
          default_password: '12345678',
          headers: {
            'Content-Type': 'application/json'
          }// 仅在同意时使用
        })

        this.$notify({
          title: '成功',
          message: data.action,
          type: 'success',
          duration: 5000
        })

        // 刷新列表
        await this.fetchResetRequests()
      } catch (error) {
        const message = error.response?.data?.detail ||
                       error.response?.data?.message ||
                       '操作失败，请稍后重试'
        this.$notify.error({
          title: '错误',
          message,
          duration: 5000
        })
      } finally {
        if (request) {
          request.isApproving = false
          request.isRejecting = false
        }
      }
    }
  }
}
</script>

<style scoped>
.admin-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.admin-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.admin-title {
  margin-bottom: 24px;
  color: #303133;
  font-size: 20px;
  font-weight: 500;
}

.filter-section {
  margin-bottom: 20px;
}

.request-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.request-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  transition: all 0.3s;
}

.request-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.request-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 500;
  color: #303133;
}

.role{
  background: #f0f9eb;
  color: #67c23a;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.contact-info {
  color: #606266;
  font-size: 14px;
}

.request-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 13px;
  color: #909399;
}

.status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status.pending {
  background: #fdf6ec;
  color: #e6a23c;
}

.status.processed {
  background: #f0f9eb;
  color: #67c23a;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}
</style>
